﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EventSys.BussinesEntities;
using System.Web.Security;
using WebMatrix.WebData;
using EventSys.MVC4Web.Models;
using System.Net.Mail;
using EventSys.MVC4Web;

/////////////

using EventSys.BussinesLogic;
using Microsoft.Practices.Unity;

namespace EventSys.MVC4Web.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        [Dependency]
        public Iwebpages_MembershipService member_Service { get; set; }

        
        public ActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult RecuperarContraseña()
        {
            return View();
        }

        [HttpPost]
        public ActionResult RecuperarContraseña(string usuario)
        {
            //verificar usuario si existe en bd
            var user = Membership.GetUser(usuario);
            if (user == null)
            {
                TempData["Message"] = "El usuario no existe";
            }
            else
            {
                //generate password token
                var token = WebSecurity.GeneratePasswordResetToken(usuario);
                //create url with above token
                var resetLink = "<a href='" + Url.Action("ResetPassword", "Login", new { un = usuario, rt = token }, "http") + "'>Reset Password</a>";
                //get user emailid

                UsersContext db = new UsersContext();//accesar a las tablas del member
                var emailid =
                    (from i in db.UserProfiles
                     where i.UserName == usuario
                     select i.Correo).FirstOrDefault();
                //send mail
                string subject = "Recuperación de correo" + "-" + "EvenSys-UPN";
                string body = "<b>Please find the Password Reset Token</b><br/>" + resetLink;
                try
                {
                    SendEMail(emailid, subject, body);
                    TempData["Message"] = "Email Enviado correctamente";
                }
                catch (Exception ex)
                {
                    TempData["Message"] = "Error al enviar el correo" + ex.Message;
                }
                //only for testing
                TempData["Message"] = resetLink;
            }

            return View();

        }
        private void SendEMail(string emailid, string subject, string body)
        {
            SmtpClient client = new SmtpClient();
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = true;
            client.Host = "smtp.gmail.com";
            client.Port = 587;

            //correo de origen
            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("jorgegonzales868@gmail.com", "jorgegonzales2013");
            client.UseDefaultCredentials = false;
            client.Credentials = credentials;

            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("xxxxx@gmail.com");
            msg.To.Add(new MailAddress(emailid));

            msg.Subject = subject;
            msg.IsBodyHtml = true;
            msg.Body = body;

            client.Send(msg);
        }

        [AllowAnonymous]
        public ActionResult ResetPassword(string un, string rt)
        {
            UsersContext db = new UsersContext();
                        
            //TODO: Check the un and rt matching and then perform following
            //get userid of received username
            var userid = (from i in db.UserProfiles
                          where i.UserName == un
                          select i.UserId).FirstOrDefault();
            //check userid and token matches.- aqui traer las tabla del webpages_menbership
            bool any = (from j in member_Service.MostrarTodos()
                        where (j.UserId == userid)
                        && (j.PasswordVerificationToken == rt)
                        //&& (j.PasswordVerificationTokenExpirationDate < DateTime.Now)
                        select j).Any();

            if (any == true)
            {
                //generate random password
                string newpassword = GenerateRandomPassword(6);
                //reset password
                bool response = WebSecurity.ResetPassword(rt, newpassword);
                if (response == true)
                {
                    //get user emailid to send password
                    var emailid = (from i in db.UserProfiles
                                   where i.UserName == un
                                   select i.Correo).FirstOrDefault();
                    //send email
                    string subject = "Nueva Contraseña-EventSys";
                    string body = "<b>Esta es su nueva contraseña de ingreso al sistema</b><br/>" + newpassword; //edit it
                    try
                    {
                        SendEMail(emailid, subject, body);
                        TempData["Message"] = "Mail Enviado";
                    }
                    catch (Exception ex)
                    {
                        TempData["Message"] = "Error occured while sending email." + ex.Message;
                    }

                    //display message
                    TempData["Message"] = "Su nuena contraseña a sido enviada correctamente..." + newpassword;
                }
                else
                {
                    TempData["Message"] = "Hey, avoid random request on this page.";
                }
            }
            else
            {
                TempData["Message"] = "Username and token not maching.";
            }

            return View();
        }
         private string GenerateRandomPassword(int length)
{
    string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-*&#+";
    char[] chars = new char[length];
    Random rd = new Random();
    for (int i = 0; i < length; i++)
    {
        chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
    }
    return new string(chars);
}



            

    }
}
